import { WeApp } from '../../../common/common';
import { config } from '../../../etc/config';
import * as __ from '../../../assets/plugins/underscore.js';
import tools from '../../../common/tools';
import httpClient from '../../../common/http-client';
import wxService from '../../../common/wxService';
import { IEnterpriseApply } from '../../../model/user';
import utils from '../../../utils/utils';
import * as wux from '../../../assets/components/wux';
import wxValidate from '../../../common/wxValidate';
import { MlcEnum } from '../../../model/enum';



const app = getApp();
interface VerAuthIndexPageData {
	steps?: Array<{
		text?: string,
		sub?: string,
		icon?: string
	}>,
	btnDisabled?: boolean,
	btnLoading?: boolean,
	currStep?: number,
	apply?: IEnterpriseApply,
	updataFile?: Array<{ url: string, path: string }>
}

interface VerAuthIndexPage extends IPage {
}

class VerAuthIndexPage {
	updataFile: Array<{ url: string, path: string }> = [];
	private steps = [
		{
			text: '填写信息',
			icon: 'http://r.59im.com/wx/icon/company_edit_infor_icon@2x.png'
		},
		{
			text: '上传图片',
			icon: 'http://r.59im.com/wx/icon/company_photo_icon@2x.png'
		},
		{
			text: '等待审核',
			icon: 'http://r.59im.com/wx/icon/company_wait_icon@2x.png'
		},
		{
			text: '认证成功',
			icon: 'http://r.59im.com/wx/icon/company_success_icon@2x.png'
		}
	];

	private WxValidate;

	public data: VerAuthIndexPageData = {
		steps: this.steps,
		apply: {}
	}


	loadData() {
		wxService.showLoading();
		let sd = {}
		sd['currStep'] = 0;
		httpClient.get<IEnterpriseApply>(config.user.apply_get)
			.then(res => {
				if (res.succeed) {
					if (res.value.imgs) {
						this.updataFile = res.value.imgs.map(item => {
							return {
								url: config.domain + item,
								path: item
							}
						});
						sd['updataFile'] = this.updataFile;
					}
					sd['apply'] = res.value;
					if (res.value.status != MlcEnum.UserEnterpriseStatus.审核通过) {
						sd['currStep'] = 2;
						if (res.value.status == MlcEnum.UserEnterpriseStatus.审核未通过) {
							sd['steps[2].text'] = '审核未通过'
						}
					}
					this.setData(sd);
				} else {
					utils.showToastErr(res.msg);
				}
				wx.hideLoading();
			})
			.catch(e => {
				wx.hideLoading();
				this.setData(sd);
			})
	}

	onShow() {
	}

	public onLoad(options) {
		if (options.formOrder) {
			this.setData({
				formOrder: options.formOrder
			})
		}
		this.WxValidate = wxValidate({
			name: {
				required: true,
				minlength: 2,
				maxlength: 100,
			},
			phone: {
				required: true
			},
			address: {
				required: true,
				minlength: 2,
				maxlength: 200,
			},
		},
			{
				name: {
					required: '请输入姓名',
					minlength: '企业名称最少2个字符',
					maxlength: '姓名最多输入6个字符'
				},
				phone: {
					required: '请输入注册电话'
				},
				address: {
					required: '请输入详细地址',
					minlength: '详细地址最少需要2个字符',
					maxlength: '详细地址最多输入200个字符'
				}
			});

		this.loadData();
	}


	nextStepEventHanlder(e) {
		e.detail.value = this.data.apply || {};
		if (!this.WxValidate.checkForm(e)) {
			const error: { msg: string } = this.WxValidate.errorList[0];
			utils.showErrorToptips(error)
			return false;
		}
		this.setData({
			currStep: this.data.currStep + 1
		})
	}

	bindKeyInput(e) {
		const key = e.target.dataset.key;
		let data = {};
		let value = e.detail.value;
		data[`apply.${key}`] = value;
		this.setData(data);
	}

	updataFileEvent(e) {
		wxService.chooseImage({
			count: 1,
			sizeType: ['compressed'],
			//sourceType: ['album']
		}).then((res: wx.ChooseImageResult) => {
			wxService.showLoading('上传中')
			console.log('url:' + config.res.uploadImg);
			wxService.uploadFile({
				header: { 'content-type': 'multipart/form-data', token: httpClient.getToken() },
				url: config.res.uploadImg,
				filePath: res.tempFilePaths[0],
				name: 'upfile'
			})
				.then((ur: wx.UploadFileResult) => {
					wx.hideLoading();
					var data: { succeed?: boolean, value: { url: string, path: string } } = JSON.parse(ur.data);
					if (data.succeed) {
						this.updataFile.push(data.value);
						this.setData({
							'updataFile': this.updataFile
						})
					} else {
						wxService.showToast('上传失败')
						console.log(ur.data);
					}
				}).catch(e => {
					wx.hideLoading();
					wxService.showToast('上传失败!!')
					console.log(JSON.stringify(e));
				})
		})
	}


	submitForm(e) {
		const apply = this.data.apply;
		if (this.updataFile.length == 0) {
			utils.showErrorToptips({ msg: '到少上传一张证件图' });
			return;
		}
		apply.imgs = this.updataFile.map(item => {
			return item.path;
		});
		utils.setBtnStatus(this);
		httpClient.post(config.user.apply, apply)
			.then(res => {
				utils.setBtnStatus(this);
				if (res.succeed) {
					let sd = {};
					sd['currStep'] = 2;
					sd['apply.status'] = MlcEnum.UserEnterpriseStatus.等待审核;
					this.setData(sd);
				} else {
					wxService.showToast(res.msg);
				}
			}).catch(e => {
				console.log(JSON.stringify(e));
			})
	}

	uploadAgainEventHanlder() {
		let sd = {};
		sd['currStep'] = 0;
		sd['isAgree'] = true;
		sd['steps[2].text'] = '等待审核'
		this.setData(sd)
	}

	clauseEvent(e) {
		wxService.navigateTo('../clause/index')
	}


	showActionSheet(e) {
		const target = e.currentTarget.dataset;
		wxService.showActionSheet({ itemList: ['称除'], itemColor: '#1724ff' })
			.then((res: wx.ShowActionSheetResult) => {
				if (res.tapIndex == 0) {
					this.updataFile.splice(target.index, 1);
					this.setData({
						'updataFile': this.updataFile
					})
				}
			})
	}


}

Page(new VerAuthIndexPage());
